package com.example.demo.Service.ServerImpl;

import com.example.demo.Service.AdministratorService;
import com.example.demo.repository.dao.AdministratorDao;
import com.example.demo.repository.domain.Administrator;
import com.example.demo.util.ImageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static com.example.demo.util.MD5.encode;

/**
 * @author ZhangKe
 * @Description
 * @date 2019/7/4 9:07.
 */
@Service
public class AdministratorServiceImpl implements AdministratorService {

    @Autowired
    private AdministratorDao administratorDao;

    @Override
    public Administrator getById(int id) {
        return administratorDao.getById(id);
    }

    @Override
    public Administrator getByName(String name) {
        return administratorDao.getByName(name);
    }

    @Override
    public int register(Administrator administrator) {
        int count=administratorDao.countByName(administrator.getAdministratorName());
        if (count==0){          //用户不存在
            String password=administrator.getAdministratorPassword();
            String salt = ImageUtil.getRandomStr(20);
            administrator.setAdministratorSalt(salt);
            String password_MD5 = encode(password, salt);
            administrator.setAdministratorPassword(password_MD5);
            return administratorDao.insert(administrator);
        }else{
            return 0;       //用户已存在
        }
    }

    @Override
    public int login(String name, String password) {
        Administrator result=administratorDao.getByName(name);//用户名：customerName的用户是否存在：null不存在，反之存在
        if (result==null){
            return -1;
        }else{  //用户存在
            String salt = result.getAdministratorSalt();
            String password_MD5 = encode(password, salt);
            if (password_MD5.equals(result.getAdministratorPassword())){   //用户存在，并且密码正确
                return 1;
            }else{          //用户存在，但是密码不正确
                return 0;
            }
        }
    }
}
